<?php

namespace App\Admin\Controllers;

use Illuminate\Http\Request;
use App\Modules\Blog\Http\Resources\CateResource;

use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Support\Arr;
use Encore\Admin\Facades\Admin;
use Illuminate\Routing\Controller;
use App\Admin\Forms\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Form;
use Encore\Admin\Show;
use Encore\Admin\Tree;
use Encore\Admin\Widgets\Box;
use Encore\Admin\Layout\Row;
use Encore\Admin\Layout\Column;
use Illuminate\Support\Facades\Auth;

class CateController extends Controller
{

    /**
     * Module slug
     */
    protected $module;
    protected $model;
    protected $title;
    protected $group = true;

    public function index(Content $content, Request $request)
    {

        $model = $this->model;
        $module = $this->module;
        $c_url = $module['slug'] . '.' . Str::slug(get_class(basename($this)));
        $this->table = $table = $this->model->getTable();
        $this->sets = $sets = (new \App\Models\Set())->where('name', $table . '.' . get_class($this->model))->first();
        if (empty($sets)) {
            $sets = config('tables.' . $table . '.sets_form_default') ?? [];
            $seturl = route('admin.set.create', ['name' => $table . '.' . get_class($this->model)]);
        } else {
            $seturl = route('admin.set.edit', ['set' => $sets->id]);
        }
        $this->desc['index'] = "<a href='{$seturl}'>设置</a>";

        return $content
            ->breadcrumb(['text' => $sets['title'] . '管理'])
            ->title($sets['title'] . '管理')
            ->description($this->desc['index'])
            ->row(function (Row $row)  use ($model, $sets, $c_url) {
                $row->column(6, $this->treeView()->render());
                $row->column(6, function (Column $column) use ($model, $sets, $c_url) {    //create部分

                    $form = new \Encore\Admin\Widgets\Form($model);
                    $form->action(route('admin.' . $c_url . '.store'));
                    //不允许生成或修改时改变parent_id,防止次序混乱
                    $form->text('title', '分类名')->rules('required');
                    $form->text('name', '标识')->rules('required|unique:cates|regex:/^[A-Za-z][A-Za-z0-9_]+$/');
                    if (empty($sets['disable_group'])) {
                        $form->tags('groups', '分组');
                    }
                    if (empty($sets['disable_publish'])) {
                        $form->switch('publish', '允许发布')->default(1)->states([
                            'on'  => ['value' => 1, 'text' => '是'],
                            'off' => ['value' => 0, 'text' => '否'],
                        ]);
                    }
                    $column->append((new Box(trans('admin.new'), $form))->style('success'));
                });
            });
    }


    public function form()
    {
        $form = new Form($this->model);
        $sets = $this->sets;
        $form->display('id', 'ID');
        $form->text('title', '分类名')->rules('required');
        $form->text('name', '标识')->rules('required|unique:cates,{{id}}|regex:/^[A-Za-z][A-Za-z0-9_]+$/');
        if (empty($sets['disable_group'])) {
            $form->tags('groups', '分组');
        }
        if (empty($sets['disable_publish'])) {
            $form->switch('publish', '允许发布')->default(1)->states([
                'on'  => ['value' => 1, 'text' => '是'],
                'off' => ['value' => 0, 'text' => '否'],
            ]);
        }
        return $form;
    }

    /**
     * Store a newly created resource in storage.
     *
     * @return mixed
     */
    public function store(Request $request)
    {
        return $this->form()->store();
    }
    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $model = $this->model;
        $data = $model->findOrFail($id);
        $result['data'] =  (new CateResource($data))->resolve();
        $result['module'] = get_module($this->mslug);
        return json_ok($result);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit(Content $content, $id)
    {
        return $content
            ->title('标题')
            ->description('测试')
            ->body($this->form()->edit($id));
    }


    public function update($id)
    {
        return $this->form()->update($id);
    }



    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        return $this->form()->destroy($id);
    }


    /**
     * @return \Encore\Admin\Tree
     */
    protected function treeView()
    {
        $module = $this->module;
        $model = $this->model;
        $sets = $this->sets;
        $canset =  empty($this->sets['set']) ? 'admin.tree.catebranch' : 'admin.tree.catebranchset';

        return $model->tree(function (Tree $tree) use ($canset) {
            $tree->setView([
                'tree'   => 'admin::tree',
                'branch' => $canset,
            ]);
            $tree->disableCreate();
            $tree->branch(function ($branch) {
                $payload = "&nbsp;<strong>{$branch['title']}</strong> -- {$branch['name']}";
                return $payload;
            });
        });
    }
}
